package org.dromara.patrol.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.enums.NoticeMessageType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.patrol.domain.PatrolSnapImg;
import org.dromara.patrol.domain.PatrolSnapRecord;
import org.dromara.patrol.domain.bo.PatrolSnapRecordBo;
import org.dromara.patrol.domain.vo.PatrolSnapRecordVo;
import org.dromara.patrol.mapper.PatrolSnapImgMapper;
import org.dromara.patrol.mapper.PatrolSnapRecordMapper;
import org.dromara.patrol.service.IPatrolSnapRecordService;
import org.dromara.system.api.RemoteMessageService;
import org.dromara.system.api.RemoteUserService;
import org.dromara.system.api.domain.bo.RemoteMessageBo;
import org.springframework.stereotype.Service;


import java.util.*;
import java.util.stream.Collectors;

/**
 * 巡店管理-处理记录Service业务层处理
 *
 * @author LionLi
 * @date 2024-03-27
 */
@RequiredArgsConstructor
@Service
public class PatrolSnapRecordServiceImpl implements IPatrolSnapRecordService {

    private final PatrolSnapRecordMapper baseMapper;


    private final PatrolSnapImgMapper patrolSnapImgMapper;

    @DubboReference
    private RemoteUserService remoteUserService;


    @DubboReference
    private RemoteMessageService remoteMessageService;

    /**
     * 查询巡店管理-处理记录
     */
    @Override
    public PatrolSnapRecordVo queryById(Long recordId){
        return baseMapper.selectVoById(recordId);
    }

    /**
     * 查询巡店管理-处理记录列表
     */
    @Override
    public TableDataInfo<PatrolSnapRecordVo> queryPageList(PatrolSnapRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PatrolSnapRecord> lqw = buildQueryWrapper(bo);
        Page<PatrolSnapRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<PatrolSnapRecordVo> records = result.getRecords();
        if (CollectionUtils.isEmpty(records)){
            TableDataInfo.build(result);
        }
        List<Long> userIds = records.stream().map(PatrolSnapRecordVo::getCreateBy).collect(Collectors.toList());
        Map<Long, String> userNameMap = remoteUserService.selectNickNameByIds(userIds);
        result.getRecords().forEach(item -> {
            if (ObjUtil.isNotNull(item)
                    && ObjUtil.isNotNull(item.getCreateBy())) {
                item.setRecordName(userNameMap.get(item.getCreateBy()));
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询巡店管理-处理记录列表
     */
    @Override
    public List<PatrolSnapRecordVo> queryList(PatrolSnapRecordBo bo) {
        LambdaQueryWrapper<PatrolSnapRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PatrolSnapRecord> buildQueryWrapper(PatrolSnapRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PatrolSnapRecord> lqw = Wrappers.lambdaQuery();
        //巡店图片的id
        lqw.eq(bo.getSnapImageId() != null, PatrolSnapRecord::getSnapImageId, bo.getSnapImageId());
        lqw.orderByDesc(PatrolSnapRecord::getCreateTime);
        return lqw;
    }

    /**
     * 新增巡店管理-处理记录
     */
    @Override
    @GlobalTransactional
    public Boolean insertByBo(PatrolSnapRecordBo bo) {
        PatrolSnapRecord add = MapstructUtils.convert(bo, PatrolSnapRecord.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setRecordId(add.getRecordId());
            //修改照片列表的状态
            updateSnapImage(bo.getSnapImageId());

            /**
             * 发生消息通知
             */
            sendMessage(add);
        }
        return flag;
    }

    private void sendMessage(PatrolSnapRecord add) {
        String atUserIds = add.getAtUserIds();
        if (StringUtils.isNotEmpty(atUserIds)){
         //把这个字符串通过逗号切分
            List<String> userIds = StringUtils.splitList(atUserIds);
            List<RemoteMessageBo> list =new ArrayList<>();
            //过滤调和da
            userIds.forEach(item -> {
                RemoteMessageBo remoteMessageBo = new RemoteMessageBo();
                remoteMessageBo.setSendId(LoginHelper.getUserId());
                remoteMessageBo.setType(NoticeMessageType.SNAP_PATROL_ISSUE_MSH_PUSH);
                remoteMessageBo.setMessageContent(NoticeMessageType.SNAP_PATROL_ISSUE_MSH_PUSH.getDesc());
                remoteMessageBo.setTitle(NoticeMessageType.SNAP_PATROL_ISSUE_MSH_PUSH.getTitle());
                remoteMessageBo.setStatus("0");
                //访问地址
                remoteMessageBo.setUrl("/patrol/snap/image/" + add.getSnapImageId());
                remoteMessageBo.setRecordId(Long.parseLong(item));
                list.add(remoteMessageBo);
            });
            remoteMessageService.insertBatchByBo(list);
        }
    }

    private void updateSnapImage(Long snapImageId) {
        PatrolSnapImg patrolSnapImg = patrolSnapImgMapper.selectById(snapImageId);
        if (ObjUtil.isNull(patrolSnapImg)) {
          throw  new ServiceException("参数错误");
        }
        patrolSnapImg.setInspectStatus("INSPECTED");
        patrolSnapImgMapper.updateById(patrolSnapImg);
    }

    /**
     * 修改巡店管理-处理记录
     */
    @Override
    public Boolean updateByBo(PatrolSnapRecordBo bo) {
        PatrolSnapRecord update = MapstructUtils.convert(bo, PatrolSnapRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PatrolSnapRecord entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除巡店管理-处理记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
